package com.neiquan.backstage.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ViewPermissionFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpReq = (HttpServletRequest) req;
		HttpServletResponse httpResp = (HttpServletResponse) resp;
		String page = getPage(httpReq);
		// 孵化器页面
		try {
			if (UserViewPermissionChecker.canAccessPage(page, httpReq)) {
				filterChain.doFilter(req, resp);
			}
		} catch (NotLoginedException e) {
			UserViewPermissionChecker.sendRedirectPageLogin(httpReq, httpResp);
		} catch (PermissionDeniedException e) {
			UserViewPermissionChecker.sendRedirectPagePermissionDenied(httpReq, httpResp);
		}
	}

	private static String getPage(HttpServletRequest httpReq) {
		return httpReq.getRequestURI().replaceFirst("^" + httpReq.getContextPath(), "");
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
	}
}
